//
//  Api.Response.swift
//  App
//
//  Created by yuany on 2020/1/6.
//

import Foundation
import Vapor

extension Api {
    static var emptyResponse = Response<Empty>()
    
    struct Empty: Content {}
    
    struct Response<T: Content>: Content {
        let status: Code
        let message: String
        let data: T?
        
        init(data: T? = nil) {
            status = .ok
            message = status.desc
            self.data = data
        }
        
        static func success(_ data: T) -> Response<T> {
            return Response(data: data)
        }
    }
}

extension Request {
    func toJson() throws -> EventLoopFuture<Response> {
        Api.emptyResponse.encodeResponse(for: self)
    }
    
    func toJson<T: Content>(with content: T) throws -> EventLoopFuture<Response> {
        Api.Response(data: content).encodeResponse(for: self)
    }
}

extension EventLoopFuture where Value: Content {
    func toJson(on request: Request) throws -> EventLoopFuture<Response> {
        map(Api.Response.init(data:)).encodeResponse(for: request)
    }
}

extension EventLoopFuture where Value == Void {
    func toJson(on request: Request) throws -> EventLoopFuture<Response> {
        transform(to: Api.emptyResponse).encodeResponse(for: request)
//        map { _ in Api.emptyResponse }.encodeResponse(for: request)
    }
}
